package com.example.wuyeguanli.tools;

import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.wuyeguanli.R;
import com.example.wuyeguanli.entiy.VisitInfo;
import com.google.zxing.BarcodeFormat;
import com.journeyapps.barcodescanner.BarcodeEncoder;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class VisitInfoAdapter extends RecyclerView.Adapter<VisitInfoAdapter.VisitInfoViewHolder> {
    private List<VisitInfo> visitInfos;
    private Context context;

    public VisitInfoAdapter(List<VisitInfo> visitInfos, Context context) {
        this.visitInfos = visitInfos;
        this.context = context;
    }

    @NonNull
    @Override
    public VisitInfoViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(context).inflate(R.layout.visitorlist_windows, parent, false);
        return new VisitInfoViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull VisitInfoViewHolder holder, int position) {
        VisitInfo currentItem = visitInfos.get(position);

        holder.visitorNum.setText(currentItem.getVisitorId());
        holder.visitorName.setText(currentItem.getVisitorName());
        holder.visitorText.setText(currentItem.getVisitPurpose());

        // 解析并格式化时间
        String startTimeStr = formatDateTime(currentItem.getVisitStartTime());
        String endTimeStr = formatDateTime(currentItem.getVisitEndTime());
        holder.visitorTime.setText(String.format("%s 至 %s", startTimeStr, endTimeStr));

        // 判断并显示凭证状态
        try {
            SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.getDefault());
            Date startDate = isoFormat.parse(currentItem.getVisitStartTime());
            Date endDate = isoFormat.parse(currentItem.getVisitEndTime());
            Date now = new Date();

            if (now.before(startDate)) {
                holder.stateVisitorImage.setText("尚未生效");
                holder.stateVisitorImage.setTextColor(Color.parseColor("#FFA500")); // Orange
            } else if (now.after(endDate)) {
                holder.stateVisitorImage.setText("已过期");
                holder.stateVisitorImage.setTextColor(Color.RED);
            } else {
                holder.stateVisitorImage.setText("凭证有效");
                holder.stateVisitorImage.setTextColor(Color.parseColor("#28a745")); // Green
            }
        } catch (ParseException e) {
            holder.stateVisitorImage.setText("时间格式错误");
            holder.stateVisitorImage.setTextColor(Color.GRAY);
            e.printStackTrace();
        }


        String qrPayload = currentItem.getQrCodePayload();

        if (qrPayload != null && !qrPayload.isEmpty()) {
            holder.visitorImage.setVisibility(View.VISIBLE);
            // --- 核心修改在这里 ---
            try {
                // 1. 生成一个小的预览图 (例如 200x200)
                Bitmap previewBitmap = new BarcodeEncoder().encodeBitmap(qrPayload, BarcodeFormat.QR_CODE, 200, 200);
                holder.visitorImage.setImageBitmap(previewBitmap);

                // 2. 设置点击监听器，点击后生成并显示高清大图
                holder.visitorImage.setOnClickListener(v -> {
                    showQrCodeDialog(qrPayload, context); // 调用原来的弹窗方法显示高清图
                });
            } catch (Exception e) {
                holder.visitorImage.setVisibility(View.GONE); // 生成失败则隐藏
            }
        } else {
            holder.visitorImage.setVisibility(View.GONE);
        }
    }

    private String formatDateTime(String isoDateTime) {
        try {
            SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.getDefault());
            SimpleDateFormat outputFormat = new SimpleDateFormat("MM-dd HH:mm", Locale.getDefault());
            Date date = inputFormat.parse(isoDateTime);
            return outputFormat.format(date);
        } catch (Exception e) {
            return "N/A";
        }
    }

    private void showQrCodeDialog(String data, Context context) {
        try {
            BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
            Bitmap bitmap = barcodeEncoder.encodeBitmap(data, BarcodeFormat.QR_CODE, 600, 600);
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            LayoutInflater inflater = LayoutInflater.from(context);
            View dialogView = inflater.inflate(R.layout.dialog_qr_code, null);
            ImageView imageViewQrCode = dialogView.findViewById(R.id.image_view_qr_code);
            imageViewQrCode.setImageBitmap(bitmap);
            builder.setView(dialogView);
            builder.setPositiveButton("关闭", (dialog, which) -> dialog.dismiss());
            builder.create().show();
        } catch (Exception e) {
            Toast.makeText(context, "生成二维码失败", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public int getItemCount() {
        return visitInfos.size();
    }

    public static class VisitInfoViewHolder extends RecyclerView.ViewHolder {
        TextView visitorNum, visitorName, visitorText, visitorTime, stateVisitorImage;
        ImageView visitorImage;

        public VisitInfoViewHolder(@NonNull View itemView) {
            super(itemView);
            visitorNum = itemView.findViewById(R.id.visitor_num);
            visitorName = itemView.findViewById(R.id.visitor_name);
            visitorText = itemView.findViewById(R.id.visitor_text);
            visitorTime = itemView.findViewById(R.id.visitor_time);
            stateVisitorImage = itemView.findViewById(R.id.state_visitor_image);
            visitorImage = itemView.findViewById(R.id.visitor_image);
        }
    }
}